
package com.sausageking.auth;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;

import com.sausageking.shared.Consumer;
import com.sausageking.shared.LoginToken;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {

    String email = "";
    String password = "";
    email = req.getParameter("email");
    password = req.getParameter("password");

    String passwordHash = UserLoginUtil.generatePasswordHash(password);

    // Check whether email/password is valid.
    ConsumerDao consumerDao = new ConsumerDao();
    Consumer consumer;
    try {
      consumer = consumerDao.getConsumerByEmail(email);
      resp.setContentType("text/plain");
      if (consumer == null || consumer.getPassword().equals(passwordHash)) {
        resp.getWriter().println(
            "The user email/password is valid: " + consumer.getEmail());
        loginUser(consumer, req, resp);
        String destination = "/myoffers";
        resp.sendRedirect(resp.encodeRedirectURL(destination));
      } else {
        resp.getWriter().println("Wrong password");
      }
    } catch (NotFoundException e) {
      resp.getWriter().println("The user does not exist.");
    }
  }

  /**
   * Login a user - (1) Write the session attribute user (2) Generate a login
   * token in the datastore (3) Place the generated token in the cookie.
   */
  private void loginUser(Consumer consumer, HttpServletRequest httpRequest,
      HttpServletResponse httpResponse) {
    LoginTokenDao loginTokenDao = new LoginTokenDao();
    Key<LoginToken> loginTokenKey = loginTokenDao.setupNewLoginToken(consumer);

    // Set user attribute in session.
    httpRequest.getSession().setAttribute("consumer", consumer);

    // Place a new login token in the cookie.
    Cookie tokenCookie = new Cookie("loginToken", loginTokenKey.toString());
    tokenCookie.setPath("/offersticker");
    tokenCookie.setMaxAge(Integer.MAX_VALUE);
    httpResponse.addCookie(tokenCookie);
  }
}
